package cn.windy.samary.module.abstracts.controller;

import cn.windy.samary.module.admin.entity.User;
import cn.windy.samary.utils.ShiroUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zyl
 * @date 2018/5/10 11:02
 */
public class AbstractController {

    public User getUser() {
        return ShiroUtils.getUser();
    }

    public String getUserId() {
        return getUser().getId();
    }

    public String getUsername() {
        return getUser().getUsername();
    }

    /**
     * 返回前台页面,以controller中类requestmapping的值为基础路径，
     * 需确保类requestmapping的值和前台文件见对应
     *
     * @param request
     * @param response
     * @param model
     * @param path     路径参数，多级路径以"_"分开
     * @return 起始路径为继承controller中类requestmapping的值
     */
    @GetMapping(value = "/getpage/{path}")
    public Object getpage(HttpServletRequest request, HttpServletResponse response,
                          Model model, @PathVariable("path") String path) {
        String servletPath = request.getServletPath();
        String p = servletPath.substring(0, servletPath.indexOf("getpage")) + path.replaceAll("_", "/");
        return p;
    }

    /**
     * 获取基础路径
     */
    public String getBasePath(HttpServletRequest request) {
        if (request != null) {
            String path = request.getContextPath();
            return request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + path + "/";
        }
        return null;
    }
}
